import {
  HTTP
} from '../utils/http.js'

class ClassicModel extends HTTP {
  // 获取最新一期书刊数据
  getLatest(sCallback) {
    this.request({
      url: '/classic/latest',
      success: (res) => {
        let key = this._createClassicKey(res.index)
        wx.setStorageSync(key, res)
        this._setLatestIndex(res.index)
        sCallback(res)
      }
    })
  }

  // 获取我点赞的书刊
  getMyFavor(success) {
    const params = {
      url: 'classic/favor',
      success: success
    }
    this.request(params)
  }

  getById(cid, type, success) {
    let params = {
      url: `classic/${type}/${cid}`,
      success: success
    }
    this.request(params)
  }


  // 获取书刊数据
  getClassic(index, NextOrPrevious, sCallback) {
    let key = NextOrPrevious === 'next' ? this._createClassicKey(index + 1) : this._createClassicKey(index - 1)
    let classic = wx.getStorageSync(key)
    if (!classic) {
      this.request({
        url: `classic/${index}/${NextOrPrevious}`,
        success: (res) => {
          wx.setStorageSync(key, res)
          sCallback(res)
        }
      })
    } else {
      sCallback(classic)
    }
  }

  // 是否是第一期书刊
  isFirst(index) {
    return index === 1 ? true : false
  }

  // 是否是最新一期书刊
  isLatest(index) {
    let latesIndex = this._getLatestIndex()
    return latesIndex === index ? true : false
  }

  /**
   * 在缓存中存放最新一期的期数
   */
  _setLatestIndex(index) {
    wx.setStorageSync('latest-index', index)
  }

  // 获取在缓存中存放最新一期的期数
  _getLatestIndex() {
    return wx.getStorageSync('latest-index')
  }

  _createClassicKey(index) {
    return `classic-${index}`
  }
}

export {
  ClassicModel
}